package com.djk.daily.thread.threadobjectclasscommonmethods;

import java.util.Date;
import java.util.LinkedList;

/**
 * @Description 用wait/notify来实现生产者消费者模式
 * @Author dujunkai
 * @Date 2021/7/3 22:10
 **/
public class ProducerConsumerModel {
    public static void main(String[] args) {
        EventStorage eventStorage = new EventStorage();
        Producer producer = new Producer(eventStorage);
        Consumer consumer = new Consumer(eventStorage);
        new Thread(producer).start();
        new Thread(consumer).start();

    }
}

class Producer implements Runnable {
    private EventStorage eventStorage;

    public Producer(EventStorage eventStorage) {
        this.eventStorage = eventStorage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            eventStorage.put();
        }
    }
}

class Consumer implements Runnable {
    private EventStorage eventStorage;

    public Consumer(EventStorage eventStorage) {
        this.eventStorage = eventStorage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            eventStorage.take();
        }
    }
}

class EventStorage {
    private int maxSize;
    private LinkedList<Date> storage;

    public EventStorage() {
        this.maxSize = 10;
        this.storage = new LinkedList<>();
    }


    public synchronized void put() {
        while (storage.size() == maxSize) {
            try {
                System.out.println("仓库满了，停止生产");
                wait();
                System.out.println("仓库有空缺，开始生产");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        storage.add(new Date());
        System.out.println("仓库里有了" + storage.size() + "个产品。");
        notify();
    }

    public synchronized void take() {
        while (storage.size() == 0) {
            try {
                System.out.println("仓库里没有产品，消费等待。");
                wait();
                System.out.println("仓库里有产品了，开始消费。");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("拿到了" + storage.poll() + ",现在仓库剩下" + storage.size());
        notify();
    }
}
